# -*- coding: utf-8 -*-
import pandas as pd, numpy as np, matplotlib.pyplot as plt


def climate_plot():
    # 直接读取 NASA 全球温度变化数据集
    df_t = pd.read_excel("GlobalTemperature.xlsx")

    # 传入世界银行气候变化数据集
    df_c = pd.read_excel("ClimateChange.xlsx")



    '''
    补充代码：
    1. 查看数据文件结构。
    2. 读取数据并对缺失值处理
    3. 对时间序列数据集进行处理并重新采样
    4. 按规定选择数据
    5. 按规定绘图
    '''
    types = ['NY.GDP.MKTP.CD','EN.ATM.CO2E.KT','EN.ATM.METH.KT.CE','EN.ATM.NOXE.KT.CE','EN.ATM.GHGO.KT.CE','EN.CLC.GHGR.MT.CE']
    index = 0
    for i in types:
        data = df_c[df_c['Series code'] == i].set_index('Country code').iloc[:,5:]
        data.replace({'..':pd.np.nan}, inplace = True)
        data = data.fillna(method='ffill', axis=1).fillna(method='bfill', axis=1)
        data.fillna(0,inplace=True)
        if(index == 0):
            df_total = data.sum()
            index = index + 1
        else:
            df_total = df_total + data.sum()
    df_total = df_total.drop([2011])#删除多余行

    df_t = df_t.set_index('Date')
    df_t.index = pd.to_datetime(df_t.index)
    df_t.fillna(0,inplace=True)
    data = df_t['1990-1':'2010-12']
    key = lambda x:x.year
    data = data.groupby(key).sum()

    df_1 = pd.concat([data[['Land Average Temperature','Land And Ocean Average Temperature']],df_total], axis=1)
    df_1.columns = ['Land Average Temperature','Land And Ocean Average Temperature','Total GHG']

    df_1 = df_1.apply(lambda x:(x-x.min())/(x.max()-x.min()))
    # 务必在绘图前子图对象，并返回 fig
    fig = plt.subplot()
    df_1.plot(title='Average and GHG',ax=fig,kind='line')
    plt.xlabel('Years')
    plt.ylabel('Values')
    plt.show()

    # 务必在绘图前设置子图对象，并返回
    fig = plt.subplot()
    df_1.plot(title='Average and GHG',ax=fig,kind='bar')
    plt.xlabel('Years')
    plt.ylabel('Values')
    plt.show()

    df_t = df_t.drop(['Land Max Temperature','Land Min Temperature'],axis=1)
    df_2 = df_t.resample('Q').sum()
    fig = plt.subplot()
    df_2.plot(title='Land And Ocean Average Temperature',ax=fig,kind='area')
    plt.xlabel('Quarters')
    plt.ylabel('Temperature')
    plt.show()

    fig = plt.subplot()
    df_2.plot(title='Land And Ocean Average Temperature',ax=fig,kind='kde')
    plt.xlabel('Values')
    plt.ylabel('Values')
    plt.show()
    # 返回 fig 对象
    return fig
#/home/shiyanlou/anaconda3/bin/python challenge7_2.py


if __name__=='__main__':
    climate_plot()


